package com.example.demo.Controller;

import com.example.demo.Dao.PersonRepository;
import com.example.demo.Dao.RecordRepository;
import com.example.demo.Entity.Person;
import com.example.demo.Entity.Record;
import com.example.demo.Qo.AreaRecord;
import com.example.demo.Qo.DayAndTemperatureQo;
import com.example.demo.Qo.PageRecordQo;
import com.example.demo.Service.RecordService;
import com.example.demo.Utils.CSVUtils;
import com.example.demo.Utils.CodeUtils;
import com.example.demo.Utils.RedisUtils;
import org.springframework.data.domain.Page;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 *
 * 	住户出入数据统计模块
 * 	住户健康信息数据统计模块
 *  所有列表可以进行综合查询，特别是时间字段，并可以排序；
 * 	所有列表可以导出excel文件或pdf文件；
 * 	住户健康状态智能预警模块
 * */
@RestController
@RequestMapping("/record")
@CrossOrigin
public class RecordController {

    @Resource
    RecordRepository recordRepository;
    @Resource
    RecordService recordService;
    @Resource
    PersonRepository personRepository;
    @Resource
    RedisUtils redisUtils;
//    展示板
    @GetMapping("/admin")
    public CodeUtils.Message getAdminRecord(){
        try {
            Map<String,Object> result  = new HashMap<>();
            int todayRecordNum =  recordRepository.customCountAllByRecordDate();
            List<Record> records = recordRepository.customFindAllOrderByDate();
            Date earlyDate  =  records.get(0).getRecordDate();
            Date lateDate  =  records.get(records.size()-1).getRecordDate();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            long startDateTime = dateFormat.parse(dateFormat.format(earlyDate)).getTime();
            long endDateTime = dateFormat.parse(dateFormat.format(lateDate)).getTime();

            int diffDate =  (int) ((endDateTime - startDateTime) / (1000 * 3600 * 24));
            double alertNum = 0;
            double safeNum = 0;
            Map<String ,Integer> areaRank = new HashMap<>();
            for (Record record:records
            ) {
                if(record.getTemperature()>=38.0){
                    alertNum++;
                    String tempArea =record.getArea();
                    areaRank.merge(tempArea, 1, Integer::sum);
                }else {
                    safeNum++;
                }
            }
//            日均高温  日均安全
            DecimalFormat format = new DecimalFormat("#.00");
            double dayRateAlertNum = Double.parseDouble(format.format(alertNum/diffDate));
            double dayRateSafeNum =  Double.parseDouble(format.format(safeNum/diffDate));

            List<Map.Entry<String,Integer>> list = new ArrayList<>(areaRank.entrySet());
            list.sort(Comparator.comparingInt(Map.Entry::getValue));
            result.put("dayAlertNum",dayRateAlertNum);
            result.put("daySafeNum",dayRateSafeNum);
            result.put("diffDate",diffDate);
            result.put("areaRank",list);
            result.put("todayRecordNum",todayRecordNum);
            return CodeUtils.Message.builder().code(20000).message(CodeUtils.Message.encodeMessageToToString(result)).build();

        }catch (Exception e)
        {
            e.printStackTrace();
            return CodeUtils.Message.builder().code(55044).message("服务器发生未知错误").build();
        }

    }




    @GetMapping("/sevenday")
    public CodeUtils.Message getSevenDay(){
        try {
            List<DayAndTemperatureQo> os =   recordRepository.getAdminDayAndNumber();
            int index = 0;
            int[] alertLine = new int[7];
            int[] safeLine = new int[7];
            int[] totalLine = new int[7];
            Date cur = os.get(0).getDate();

            for (DayAndTemperatureQo o:os
            ) {
                if (cur.compareTo(o.getDate())<0)
                {
                    cur = o.getDate();
                    index++;
                }
                if (o.getTemperature()>=38.0){
                    alertLine[index]+=1 ;
                }else if(o.getTemperature()<38.0&&o.getTemperature()!=0){
                    safeLine[index]+= 1 ;
                }
                if (o.getTemperature() != 0){
                    totalLine[index]+=1;
                }
            }
            Map<String, int[]> result = new HashMap<>(8);
            result.put("alertLine",alertLine);
            result.put("safeLine",safeLine);
            result.put("totalLine",totalLine);
            return CodeUtils.Message.builder().code(20000).message(CodeUtils.Message.encodeMessageToToString(result)).build();
        }   catch (Exception e){
            return CodeUtils.Message.builder().code(44033).message("服务器发生未知错误").build();
        }
    }
//    分页列表

    @GetMapping("/list")
    public CodeUtils.Message getRecordPageable(@RequestParam int pagenum, @RequestParam int pagesize, @RequestParam String sort, @Nullable @RequestParam String keyword){


        try {
            Page<Record> records;
            if (keyword==null|| "".equals(keyword)){
                records =  recordService.findByPageAndParams(pagenum,pagesize,sort);
            }else {
                 records =  recordService.findByPageAndKeyword(pagenum,pagesize,sort,keyword);
            }
            return CodeUtils.Message.builder().code(20000).message(
                    CodeUtils.Message.encodeMessageToToString(
                            PageRecordQo.builder().records(records.getContent())
                            .totalNum(records.getTotalElements())
                            .totalPage(records.getTotalPages())
                            .build()
                    )).build();

        }catch (Exception e){
            e.printStackTrace();
            return CodeUtils.Message.builder().code(55044).message("服务器发生未知错误").build();
        }
    }

    @GetMapping("/area")
    public CodeUtils.Message getRecordByArea(@RequestParam String area)
    {
        try {
            List<AreaRecord> records = recordRepository.findAllByArea(area);
            return CodeUtils.Message.builder().code(20000).message(CodeUtils.Message.encodeMessageToToString(records)).build();
        }catch (Exception e){
            e.printStackTrace();
            return CodeUtils.Message.builder().code(55044).message("服务器发生未知错误").build();
        }
    }

    @GetMapping("/person")
    public CodeUtils.Message getPerson(){
        try {
            return CodeUtils.Message.builder().code(20000).message(CodeUtils.Message.encodeMessageToToString(personRepository.findAll())).build();
        }catch (Exception e){
            e.printStackTrace();
            return CodeUtils.Message.builder().code(55044).message("服务器发生未知错误").build();
        }
    }


    @DeleteMapping("/person")
    public CodeUtils.Message delPerson(@RequestParam Long id){
        try {
            Person person  = personRepository.findById(id).orElse(null);
            if (person == null){
                return CodeUtils.Message.builder().code(44033).message("没有找到该用户").build();
            }
            redisUtils.del(person.getUsername());
            personRepository.deleteById(id);
            return CodeUtils.Message.builder().code(20000).message(CodeUtils.Message.encodeMessageToToString("删除成功")).build();
        }catch (Exception e){
            e.printStackTrace();
            return CodeUtils.Message.builder().code(55044).message("服务器发生未知错误").build();
        }
    }

}
